import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;

public class TCPTest1 {
    //客户端
    @Test
    public void client() throws IOException{
        //创建一个socket
        InetAddress inetaddress = InetAddress.getByName("168.11.2.11");
        int port = 8989;
        Socket socket = new Socket(inetaddress, port);

        //发送数据
        OutputStream os = socket.getOutputStream();
        os.write("hello, I'm client.".getBytes());
        
        //关闭socket
        socket.close();
        os.close();
    }

    @Test
    public void server() throws IOException{
        //创建一个ServerSocket
        int port = 8989;
        ServerSocket serverSocket = new ServerSocket(port);

        //调用accept()，接收客户端socket
        Socket socket = serverSocket.accept();
        System.out.println("Server accept data.");

        //接收数据
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            //未读完
            String str = new String(buffer, 0, len);
            System.out.println(str);
        }

        System.out.println("\ndata receiving end.");


        //关闭socket.ServerSocket
        socket.close();
        is.close();
        serverSocket.close();
    }
    
}

